﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Timers;

using Timer = System.Timers.Timer;


namespace ExtensibleEventViewer.Console.Tasks
{
	internal class TaskService
	{
		private readonly Timer _timer;
		private static readonly TaskService _instance = new TaskService();
		private readonly List<TaskBase> _taskList = new List<TaskBase>();

		private TaskService()
		{
			_timer = new Timer(2000);
			_timer.Elapsed += TimerElapsed;
			_timer.AutoReset = true;
			_timer.Start();
		}

		private void TimerElapsed(object sender, ElapsedEventArgs e)
		{
			for (int i = 0; i < _taskList.Count; i++)
			{
				if (_taskList[i].ExecuteOn <= DateTime.UtcNow && !_taskList[i].Executing)
				{	
					ThreadPool.QueueUserWorkItem(_taskList[i].Execute, null);				
				}
			}
		}

		public static TaskService Instance
		{
			get
			{
				return _instance;
			}
		}

		public double Interval
		{
			get
			{
				return _timer.Interval;
			}
			set
			{
				_timer.Interval = value;
			}
		}

		public void AddTask(TaskBase task)
		{
			task.ExecutedSuccessfuly += RemoveTask;

			_taskList.Add(task);
		}

		public IEnumerable<TTaskType> SelectTasksByType<TTaskType>()
		{
			return _taskList.OfType<TTaskType>();
		}

		private void RemoveTask(TaskBase task)
		{
			if (!task.IsRescheduled || task.RescheduleInterval == TimeSpan.Zero)
			{
				_taskList.Remove(task);
			}
		}
	}
}
